<template>
    <div>
        <canvas height="47px" width="140px" id="messageCode" :style="`background-color: ${bgcc};`"
            @click="getVeri"></canvas>
    </div>
</template>

<script>
import { _getMessageCode } from "../api/toos.js"
export default {
    data() {
        return {
            str: "7562",
            bgcc: ""
        }
    },
    methods: {
        drawMessageCanvas(str) {

            this.changeBgcc()
            const canvas = document.getElementById("messageCode")
            if (!canvas?.getContext) {
                console.log("浏览器不支持canvas，请更换高版本浏览器")
                return
            } else {

                const ctx = canvas.getContext("2d")
                // console.log(ctx)
                // ctx.beginPath()
                // ctx.font("20px '黑体'")
                ctx.clearRect(0, 0, 140, 47)

                for (var i = 0; i < str.length; i++) {
                    ctx.font = '400 25px PingFangSC-Regular';
                    ctx.fillStyle = this.RunderColor()
                    ctx.fillText(str[i], this.RenNum(23, 28) * (i + 1), this.RenNum(25, 47))
                }

                for (var k = 0; k < 8; k++) {
                    ctx.beginPath()
                    ctx.moveTo(this.RenNum(0, 140), this.RenNum(0, 47))
                    ctx.lineTo(this.RenNum(0, 140), this.RenNum(0, 47))
                    ctx.strokeStyle = this.RunderColor()
                    ctx.stroke()
                }

                for (var j = 0; j < 8; j++) {
                    ctx.beginPath()
                    const x = this.RenNum(0, 140)
                    const y = this.RenNum(0, 47)
                    ctx.moveTo(x, y)
                    ctx.lineTo(x + 2, y + 2)
                    ctx.strokeStyle = this.RunderColor()
                    ctx.stroke()
                }
            }
        },
        RenNum(max, min) {
            return Math.floor(Math.random() * (max - min)) + min
        },
        RunderColor() {
            return `rgb(${this.RenNum(0, 255)}, ${this.RenNum(0, 255)}, ${this.RenNum(0, 255)})`
        },
        changeBgcc() {
            this.bgcc = this.RunderColor()
        },
        async getVeri() {
            const veri = await _getMessageCode()
            this.str = veri.data.data
            this.drawMessageCanvas(this.str)
        }
    },
    mounted() {
        this.getVeri()
    }
}
</script>

<style lang="scss" scoped></style>